<template>
  <div class="editTask">
    <el-form :model="editTaskForm" :rules="editTaskRules" ref="editTaskForm" label-width="100px" size="mini"
      :hide-required-asterisk="true">
      <el-form-item label="工单编号">
        <el-input v-model="editTaskForm.gdbh" disabled></el-input>
      </el-form-item>
      <el-form-item label="产品编号">
        <el-input v-model="editTaskForm.cpbh" disabled></el-input>
      </el-form-item>
      <el-form-item label="产品名称">
        <el-input v-model="editTaskForm.cpmc" disabled></el-input>
      </el-form-item>
      <el-form-item prop="gxbh">
        <template slot='label'>
          <span style="color: red">*</span>
          工序编号
        </template>
        <el-input v-model="editTaskForm.gxbh" disabled></el-input>
      </el-form-item>
      <el-form-item prop="gxmc">
        <template slot='label'>
          <span style="color: red">*</span>
          工序名称
        </template>
        <el-input v-model="editTaskForm.gxmc" disabled></el-input>
      </el-form-item>
      <el-form-item prop="bgqx">
        <template slot='label'>
          <span style="color: red">*</span>
          报工权限
        </template>
        <el-select v-model="editTaskForm.bgqx" multiple filterable remote disabled>
        </el-select>
      </el-form-item>
      <el-form-item prop="bgspb">
        <template slot='label'>
          <span style="color: red">*</span>
          报工数配比
        </template>
        <el-input v-model="editTaskForm.bgspb" @input='rateInput'></el-input>
      </el-form-item>
      <el-form-item prop="jhs">
        <template slot='label'>
          <span style="color: red">*</span>
          计划数
        </template>
        <el-input v-model="editTaskForm.jhs" @input='planNumInput'></el-input>
      </el-form-item>
      <el-form-item label="良品数">
        <el-input v-model="editTaskForm.lps" disabled></el-input>
      </el-form-item>
      <el-form-item label="不良品数">
        <el-input v-model="editTaskForm.blps" disabled></el-input>
      </el-form-item>
      <el-form-item prop="jhsj" style="margin-bottom:25px">
        <template slot='label'>
          <span style="color: red">*</span>
          计划开始/结束时间
        </template>
        <el-date-picker v-model="editTaskForm.jhsj" type="datetimerange" range-separator="至" start-placeholder="开始日期"
          format='yyyy-MM-dd HH:mm' value-format='yyyy-MM-dd HH:mm:ss' end-placeholder="结束日期" :picker-options="pickerOptions">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="实际开始/结束时间">
        <el-date-picker v-model="editTaskForm.sjsj" disabled type="datetimerange" range-separator="至"
          start-placeholder="开始日期" end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <!-- ====================自定义==================== -->
      <el-form-item v-for='(item, i) in customFiledList' :key="i" :label='item.chineseName' :prop="item.id"
        v-show='hiddenRule(item)'>
        <el-checkbox-group v-show="false" v-model="editTaskForm[item.id]"></el-checkbox-group>
        <template slot='label'>
          <span style="color: red" v-show="requireRsterisk(item)">*</span>
          {{ item.chineseName }}
          <el-tooltip class="item" effect="dark" :content="item.tips" placement="top" v-show='item.tips'>
            <span class="iconfont icon-wenhao wenhao"></span>
          </el-tooltip>
        </template>
        <formLibrary :formItem='item' @formItemHandle='formItemHandle' :defaultData="defaultData"
          @uploadProgress='uploadProgress' ref='formLibrary'>
        </formLibrary>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="mini" plain @click="handleCancel">取 消
        </el-button>
        <el-button type="primary" size="mini" @click="save">保 存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
  import {
    missionEdit,
    missionDetail
  } from '@/api/produceController'
  import {
    loginUserMess
  } from '@/api/loginController'
  import {
    customFieldOther,
    fillFieldMess
  } from '@/api/customFieldController'
  import formLibrary from '@/components/formLibrary'
  export default {
    data() {
      var checkNum = (rule, value, callback) => {
        let tit
        tit = rule.field == 'bgspb' ? '报工数配比' : '计划数'
        let reg = new RegExp(`^\\d+(\\.\\d{1,6})?$`)
        if (value == '') {
          return callback(new Error(`${tit}必填`));
        } else if (value == 0) {
          return callback(new Error(`${tit}必须大于0`))
        } else if (!reg.test(value)) {
          return callback(new Error('只能为数字类型且小数点后最多保留6位数字'))
        } else {
          callback()
        }
      };
      return {
        editTaskForm: {
          gdbh: '',
          cpbh: '',
          cpmc: '',
          gxbh: '',
          gxmc: '',
          bgqx: '',
          bgspb: '',
          jhs: '',
          lps: '',
          blps: '',
          jhsj: [],
          sjsj: []
        },
        editTaskRules: {
          gxbh: [{
            required: true,
          }],
          gxmc: [{
            required: true,
          }],
          bgspb: [{
            required: true,
            validator: checkNum
          }],
          blpxlb: [{
            required: true,
          }],
          jhs: [{
            required: true,
            validator: checkNum
          }],
          jhsj: [{
            required: true,
            message: "计划开始/结束时间必填",
            trigger: 'change'
          }],
        },
        pickerOptions:{
            disabledDate: time => {
                return time.getTime() < Date.parse(this.editTaskForm.jhsj[0] + '') || time.getTime() > Date.parse(this.editTaskForm.jhsj[1] + '')
            }
        },
        workOrderPlanNum: 0,
        customFiledList: [],
        defaultData: [], // 自定义字段值
        customFiledData: [],
        customState: true, // 判断单选/复选 选值是否正确
        customErrorLabel: '', // 选值错误提示语
        // 关联属性信息
        relevanceProp: [],
        userMess: {},
        uploadFlag: true,
        productSpecification: ''
      }
    },
    components: {
      formLibrary
    },
    watch: {
      editTaskForm: {
        handler() {
          this.hiddenRule('')
        },
        deep: true,
      }
    },
    mounted() {
      this.getMissionDetail({
        id: this.$route.query.id
      })
    },
    methods: {
      // 自定义字段
      getCustomFieldOther() {
        customFieldOther({
          type: 'processes'
        }).then(res => {
          this.customFiledList = []
          this.relevanceProp = []
          if (res.code == 200) {
            // 自定义字段数据
            res.data.map(item => {
              item.customFieldMess.objectsValue = item.objectsValue
              this.customFiledList.push(item.customFieldMess)
            })
            // 添加自定义字段的校验规则(是否必填)
            this.customFiledList.map(item => {
              let r = item.hidden
              item.hidden = r.replace(/\${工序./g, 'formItemData["').replace(/\}/g, '"]')
                .replace(/\${用户信息./g, 'userFormItemData["')
              item.id = item.id + ''
              let obj = {}
              if (JSON.parse(item.fieldAttribute).required && item.fieldType != 'inputNumber') {
                  obj[item.id] = [{
                      required: true,
                      message: item.chineseName + '不能为空'
                  }]
              }else if(item.fieldType == 'inputNumber'){
                const numberRule = (rule, v, callback) => {
                      let tempValue = ''
                      let index = String(this.editTaskForm[item.id]).indexOf('.')
                      tempValue = index != -1 ? String(this.editTaskForm[item.id]).slice(0,index) : String(this.editTaskForm[item.id])
                      if (!this.editTaskForm[item.id] && item.isRequired) {
                          return callback(new Error(`${item.chineseName}不能为空！`));
                      }else if(tempValue.length > 10){
                          return callback(new Error('整数位最多支持10位数字'));
                      }else if(this.editTaskForm[item.id] != undefined && !(/^[0-9]+(.[0-9]{1,6})?$/.test(this.editTaskForm[item.id]))){
                          return callback(new Error('小数点后最多保留6位数字'));
                      }else {
                          callback()
                      }
                  }
                  obj[item.id] = [{
                      validator: numberRule,
                      trigger:'blur'
                  }]
              }
              this.editTaskRules = Object.assign(this.editTaskRules, obj)
              if (item.fieldType == 'relevanceProp') {
                this.relevanceProp.push({
                  id: item.id,
                  objectFieldId: item.objectFieldId,
                  type: item.correlationField
                })
              }
            })
            this.getLoginUserMess()
          }
        })
      },
      // 用户信息
      getLoginUserMess(data) {
        loginUserMess(data).then(res => {
          this.loading = false
          if (res.code == 200) {
            this.userMess = res.data
          }
        })
      },
      // 关联对象-字段信息
      getFillFieldMess(data, fillRule, n) {
        fillFieldMess(data).then(res => {
          this.defaultData = []
          for (let key in this.editTaskForm) {
            if (Number(key)) {
              this.defaultData.push({
                customFieldId: key,
                value: this.editTaskForm[key]
              })
            }
          }
          if (res.code == 200) {
            // 如果该条数据有自定义字段
            if (res.data.customFieldVos != null) {
              /* 
                  遍历关联对象的填充规则
                  遍历该条数据的自定义字段列表
                  将填充规则中的来源值(from) 赋给 指定控件(to)
              */
              fillRule.map(item => {
                let dataArr = []
                let f = res.data.customFieldVos.find(res => {
                  return res.customFieldId == item.from
                })
                if (f != undefined) {
                  res.data.customFieldVos.map(k => {
                    if (k.customFieldId == item.from) {
                      this.editTaskForm[item.to] = k.value
                      this.defaultData = this.defaultData.filter(j => j.customFieldId != item.to)
                      this.defaultData.push({
                        customFieldId: item.to,
                        value: k.value
                      })
                    }
                  })
                } else {
                  this.editTaskForm[item.to] = ''
                  this.defaultData.map(k => {
                    if (k.customFieldId == item.to) {
                      let d = this.customFiledList.find(res => {
                        return res.id == item.to
                      })
                      if (d.fieldType == 'picture' || d.fieldType == 'upload' || d.fieldType ==
                        'selectChecked') {
                        dataArr.push({
                          customFieldId: k.customFieldId,
                          value: "[]"
                        })
                      } else {
                        dataArr.push({
                          customFieldId: k.customFieldId,
                          value: ""
                        })
                      }
                    } else {
                      dataArr.push({
                        customFieldId: k.customFieldId,
                        value: k.value
                      })
                    }
                  })
                  this.defaultData = dataArr
                }
              })
            } else {
              fillRule.map(item => {
                let dataArr = []
                this.editTaskForm[item.to] = ''
                this.defaultData.map(k => {
                  if (k.customFieldId == item.to) {
                    let d = this.customFiledList.find(res => {
                      return res.id == item.to
                    })
                    if (d.fieldType == 'picture' || d.fieldType == 'upload' || d.fieldType ==
                      'selectChecked') {
                      dataArr.push({
                        customFieldId: k.customFieldId,
                        value: "[]"
                      })
                    } else {
                      dataArr.push({
                        customFieldId: k.customFieldId,
                        value: ""
                      })
                    }
                  } else {
                    dataArr.push({
                      customFieldId: k.customFieldId,
                      value: k.value
                    })
                  }
                })
                this.defaultData = dataArr
              })
            }
            // 关联属性赋值
            this.relevanceProp.map(item => {
              if (item.objectFieldId == n) {
                this.editTaskForm[item.id] = res.data[item.type]
                this.defaultData = this.defaultData.filter(j => j.customFieldId != item.id)
                this.defaultData.push({
                  customFieldId: item.id,
                  value: res.data[item.type]
                })
              }
            })
          }
        })
      },
      // 自定义表单项数据--表单子组件传递的值
      formItemHandle(d) {
        // 子组件的值赋给表单
        this.$set(this.editTaskForm, d.name, d.value)
        // 操作的是关联对象
        if (d.relevanceObject != undefined) {
          if (d.relevanceObject.id) {
            let data = {
              id: d.relevanceObject.id,
              type: d.relevanceObject.businessObject
            }
            this.getFillFieldMess(data, d.relevanceObject.fillRule, d.name)
          } else {
            this.customFiledList.map(item => {
              if (item.objectFieldId == d.name) {
                this.editTaskForm[item.id] = ''
                this.defaultData.map(k => {
                  if (k.customFieldId == item.id || k.customFieldId == d.name) {
                    k.value = ''
                  }
                })
              }
            })
            for (let key in this.editTaskForm) {
              let ind = this.defaultData.findIndex(res => {
                return res.customFieldId == key
              })
              if (ind != -1) {
                this.$set(this.defaultData, ind, {
                  customFieldId: key,
                  value: this.editTaskForm[key]
                })
              } else {
                this.defaultData.push({
                  customFieldId: key,
                  value: this.editTaskForm[key]
                })
              }
            }
          }
        }
      },
      // 自定义隐藏设置--隐藏条件触发
      hiddenRule(d) {
        let formItemData = {
          '工序编号': this.editTaskForm.gxbh,
          '工序名称': this.editTaskForm.gxmc,
          '报工数配比': this.editTaskForm.bgspb,
          '计划数': this.editTaskForm.jhs,
          '良品数': this.editTaskForm.lps,
          '不良品数': this.editTaskForm.blps,
          '产品名称': this.editTaskForm.cpmc,
          '产品编号': this.editTaskForm.cpbh,
          '产品规格': this.productSpecification,
          '计划开始时间': this.utils.formatTime(this.editTaskForm.jhsj[0],
            'yyyy-MM-dd hh:mm:ss'),
          '计划结束时间': this.utils.formatTime(this.editTaskForm.jhsj[1],
            'yyyy-MM-dd hh:mm:ss'),
          '实际开始时间': this.utils.formatTime(this.editTaskForm.sjsj[0],
            'yyyy-MM-dd hh:mm:ss'),
          '实际结束时间': this.utils.formatTime(this.editTaskForm.sjsj[1],
            'yyyy-MM-dd hh:mm:ss')
        }
        let userFormItemData = {
          '账号': this.userMess.account,
          '姓名': this.userMess.name,
          '手机号': this.userMess.mobile,
          '角色': this.userMess.role,
        }
        this.customFiledList.map(item => {
          if (formItemData[item.chineseName] == undefined) {
            if (this.editTaskForm[item.id] != undefined) {
              formItemData[item.chineseName] = this.editTaskForm[item.id]
            } else {
              formItemData[item.chineseName] = ''
            }
          }
          if (userFormItemData[item.chineseName] == undefined) {
            if (this.editTaskForm[item.id] != undefined) {
              userFormItemData[item.chineseName] = this.editTaskForm[item.id]
            } else {
              userFormItemData[item.chineseName] = ''
            }
          }
        })
        let state = null
        try {
          state = !eval(d.hidden)
        } catch {
          state = true
        }
        //必填项字段若是被隐藏不校验
        if (this.editTaskRules[d.id]) {
            if(d.fieldType == 'inputNumber'){
                if(JSON.parse(d.fieldAttribute).required){ //inputNumber 必填 && 切换触发隐藏条件
                    d.isRequired = state
                }
            }else{
                this.editTaskRules[d.id][0].required = state
            }
        }
        return state
      },
      requireRsterisk(d) {
        if (this.editTaskRules[d.id]) {
            if(d.fieldType == 'inputNumber'){
                return JSON.parse(d.fieldAttribute).required || false
            }else{
                return this.editTaskRules[d.id][0].required || false
            }
        }
      },
      customData(v, data) {
        if (Number(v)) {
          let id = ''
          data.map(item => {
            if (item.value == v) {
              id = item.label
            }
          })
          return id
        } else {
          return v
        }
      },
      // 附件/图片上传是否完成
      uploadProgress(s) {
        this.uploadFlag = s
      },
      getMissionEdit(data) {
        missionEdit(data).then(res => {
          if (res.code == 200) {
            this.$router.push('/productionManagement/task')
            this.utils.showMsg('编辑成功', 'success')
          }
        })
      },
      getMissionDetail(data) {
        missionDetail(data).then(res => {
          if (res.code == 200) {
            this.getCustomFieldOther()
            let optionsArr = res.data.processPermissions.split(',')
            let reg = new RegExp(`^\\d+(\\.\\d{1,6})?$`)
            this.editTaskForm.gdbh = res.data.workOrderCode
            this.editTaskForm.cpbh = res.data.productCode
            this.editTaskForm.cpmc = res.data.productName
            this.editTaskForm.gxbh = res.data.processCode
            this.editTaskForm.gxmc = res.data.processName
            this.editTaskForm.bgqx = optionsArr
            this.editTaskForm.bgspb = res.data.rate
            this.editTaskForm.jhs = res.data.planedNumber
            this.editTaskForm.lps = res.data.goodProductNumber
            this.editTaskForm.blps = res.data.badProductNumber
            this.productSpecification = res.data.productSpecification
            this.workOrderPlanNum = !reg.test(res.data.planedNumber / res.data.rate) ?
              (res.data.planedNumber / res.data.rate).toFixed(6) : (res.data.planedNumber / res.data.rate)
            this.$set(this.editTaskForm, 'jhsj', [res.data.startTime, res.data.endTime])
            this.$set(this.editTaskForm, 'sjsj', [
              res.data.actualStartTime == null ? '' : res.data.actualStartTime,
              res.data.actualEndTime == null ? '' : res.data.actualEndTime
            ])
            this.customFiledData = []
            this.defaultData = []
            // 不为null说明该条数据有自定义字段，将自定义字段值初始化给表单
            if (res.data.customFieldVos != null) {
              res.data.customFieldVos.map(item => {
                this.$set(this.editTaskForm, item.customFieldId, item.value)
                this.customFiledData.push({
                  customFieldId: item.customFieldId,
                  value: item.value
                })
                this.defaultData.push({
                  customFieldId: item.customFieldId,
                  value: item.value
                })
              })
            }
          }
        })
      },

      //报工数配比改变
      rateInput(n) {
        //报工数配比与计划数小数点后长度保持一致
        let index = n.indexOf('.')
        let strLength
        if (index != -1) strLength = n.substr(index + 1).length
        this.editTaskForm.jhs = (this.workOrderPlanNum * n).toFixed(
          n.substr(n.length - 1, 1) == '0' ? strLength - 1 : strLength)
      },

      //计划数改变
      planNumInput(n) {
        //计算报工数配比过程中小数点超出6位，则取6位
        let reg = new RegExp(`^\\d+(\\.\\d{1,6})?$`)
        if (!this.workOrderPlanNum) return
        this.editTaskForm.bgspb = !reg.test(n / this.workOrderPlanNum) ?
          (n / this.workOrderPlanNum).toFixed(6) : (n / this.workOrderPlanNum)
      },
      //保存
      save() {
        this.$refs.editTaskForm.validate((valid) => {
          if (valid) {
            let data = {
              id: this.$route.query.id,
              startTime: this.editTaskForm.jhsj[0],
              planedNumber: Number(this.editTaskForm.jhs),
              rate: Number(this.editTaskForm.bgspb),
              endTime: this.editTaskForm.jhsj[1],
            }
            let customData = []
            for (let key in this.editTaskForm) {
              if (Number(key)) {
                this.customFiledList.forEach(item => {
                  if (
                    item.id == key && this.editTaskForm[key] != null &&
                    String(this.editTaskForm[key]).length
                  ) {
                    customData.push({
                      customFieldId: item.id,
                      value: this.editTaskForm[key]
                    })
                  }
                })
              }
            }
            // 关联对象后，判断单选框/复选框关联过来的值是否存在
            this.customState = true
            this.customErrorLabel = ''
            this.customFiledList.map(item => {
              // 单选框
              if (item.fieldType == 'selectRadio') {
                if (this.editTaskForm[item.id] != '' && this.editTaskForm[item.id] !=
                  undefined) {
                  let s = JSON.parse(item.checkBox).find(res => {
                    return this.editTaskForm[item.id] == res.value
                  })
                  if (s == undefined) {
                    this.customState = false
                    this.customErrorLabel = '【' + item.chineseName + '】选项值不正确'
                  }
                }
              }
              // 复选框
              if (item.fieldType == 'selectChecked') {
                if (this.editTaskForm[item.id] != '' && this.editTaskForm[item.id] !=
                  undefined && this.editTaskForm[item.id] != '[]') {
                  JSON.parse(this.editTaskForm[item.id]).map(k => {
                    let s = JSON.parse(item.checkBox).find(res => {
                      return res.value == k
                    })
                    if (s == undefined) {
                      this.customState = false
                      this.customErrorLabel = '【' + item.chineseName +
                        '】选项值不正确'
                    }
                  })
                }
              }
            })
            data.customFieldVos = customData
            if (this.customState) {
              if (this.uploadFlag) {
                this.$refs.formLibrary != undefined && this.$refs.formLibrary.map(k => {
                  k.removeData('ok')
                })
                this.getMissionEdit(data)
              } else {
                this.utils.showMsg('正在上传，请稍后', 'warning')
              }
            } else {
              this.utils.showMsg(this.customErrorLabel, 'error')
            }
          } else {
            return false;
          }
        });
      },
      // 取消
      handleCancel() {
        this.$refs.formLibrary != undefined && this.$refs.formLibrary.map(k => {
          k.removeData('cancle')
        })
        this.$router.push('/productionManagement/task')
      },
    }
  }
</script>

<style lang="less" scoped>
  .editTask {
    padding: 20px;
    height: calc(100% - 50px);
    overflow: auto;

    /deep/ .el-form {
      width: 400px;
    }

    /deep/ .el-select,
    /deep/ .el-input-number--mini,
    /deep/ .el-date-editor.el-input {
      width: 100%;
    }

    /deep/ .el-button--mini {
      padding: 7px 40px;
    }

    /deep/ .el-range-editor.el-input__inner {
      width: 100%;
    }

    /deep/ .el-range-editor .el-range-input {
      flex: 3;
    }

    /deep/ .el-date-editor .el-range-separator {
      flex: 1;
    }

    /deep/ .el-button--primary span {
      margin-left: 0px;
    }
  }
</style>